<?php
/**
 * vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
 * 
 * MY_Loader Class
 *
 * Loads global_models
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @author      Alex Loskutov (snakenf@gmail.com)
 * @category    Loader
 * @see         CI_Loader
 */
class MY_Loader extends CI_Loader {

    private $_models_path = '../models/';

    public function MY_Loader()
    {
        parent::CI_Loader();
    }

    /**
     * Set global models path
     *
     * @access  public
     * @param   string  $path path to global models from APPPATH
     * @return  bool    true if path exist, false if not exist
     **/
    public function set_models_path($path)
    {
        if (file_exists(APPPATH.$path))
        {
            $this->_models_path = $path;
            log_message('debug', 'Global models path change: '.$path);
            return true;
        }
        else
        {
        	log_message('error', 'Global models path, not exist: '.$path);
            show_error('Global models path, not exist: '.$path);
            return false;
        }
    }

	/**
     * Get global models path
     *
     * @access  public
     * @return  string	path to global models from APPPATH
     **/
    public function get_models_path()
    {
        return $this->_models_path;
    }


    /**
     * Global Model Loader
     *
     * This function lets users load and instantiate global models.
     *
     * @access	public
     * @param	string	the name of the class
     * @param	string	name for the model
     * @param	bool	database connection
     * @return	void
     */
    public function global_model($model, $name = '', $db_conn = FALSE)
    {
	if (is_array($model))
	{
	    foreach($model as $babe)
	    {
		$this->model($babe);
	    }
	    return;
	}

	if ($model == '')
	{
	    return;
	}

	// Is the model in a sub-folder? If so, parse out the filename and path.
	if (strpos($model, '/') === FALSE)
	{
	    $path = '';
	}
	else
	{
	    $x = explode('/', $model);
	    $model = end($x);
	    unset($x[count($x)-1]);
	    $path = implode('/', $x).'/';
	}

	if ($name == '')
	{
	    $name = $model;
	}

	if (in_array($name, $this->_ci_models, TRUE))
	{
	    return;
	}

	$CI =& get_instance();
	if (isset($CI->$name))
	{
	    show_error('The model name you are loading is the name of a resource that is already being used: '.$name);
	}

	$model = strtolower($model);

	if ( ! file_exists(APPPATH.$this->get_models_path().$path.$model.EXT))
	{
	    show_error('Unable to locate the model you have specified: '.$model);
	}

	if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
	{
	    if ($db_conn === TRUE)
		$db_conn = '';

	    $CI->load->database($db_conn, FALSE, TRUE);
	}

	if ( ! class_exists('Model'))
	{
	    load_class('Model', FALSE);
	}

	require_once(APPPATH.$this->get_models_path().$path.$model.EXT);

	$model = ucfirst($model);

	$CI->$name = new $model();
	$CI->$name->_assign_libraries();

	$this->_ci_models[] = $name;
    }

}
?>
